package ipad.asia.controller;

import ipad.asia.config.SecKillVO;
import ipad.asia.entity.*;
import ipad.asia.service.bbs.BbsFeign;
import ipad.asia.service.consumer.ConsumerFeign;
import ipad.asia.service.discount.DiscountFeign;
import ipad.asia.service.enterprise.EnterpriseFeign;
import ipad.asia.service.evaluate.EvaluateFeign;
import ipad.asia.service.order.OrderFeign;
import ipad.asia.service.product.ProductFeign;
import ipad.asia.service.seckill.SecKillFeign;
import ipad.asia.service.shop.ShopFeign;
import ipad.asia.utils.RandomNum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Controller
public class SecKillController {
    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private BbsFeign bbsFeign;
    @Autowired
    private DiscountFeign discountFeign;
    @Autowired
    private ConsumerFeign consumerFeign;
    @Autowired
    private EnterpriseFeign enterpriseFeign;
    @Autowired
    private ShopFeign shopFeign;
    @Autowired
    private SecKillFeign secKillFeign;
    @Autowired
    private OrderFeign orderFeign;
    @Autowired
    private RandomNum randomNum;
    @Autowired
    private EvaluateFeign evaluateFeign;
    @RequestMapping("/secKill/list")
    public String secKillList(Model model, HttpSession session) {
        List<Product> products = productFeign.all();
        List<SeckillProduct> secKillProducts = secKillFeign.products();
        List<SecKillVO> newSecKillProducts = new ArrayList<>();
        //两个产品按照id的属性合并
        for (int i = 0; i < products.size(); i++) {
            for (int j = 0; j < secKillProducts.size(); j++) {
                if (products.get(i).getId() == secKillProducts.get(j).getProductId()) {
                    SecKillVO newSecKillProduct = new SecKillVO();
                    SeckillProduct seckillProduct = secKillFeign.getById(secKillProducts.get(j).getProductId());
                    Product product = productFeign.getById(products.get(i).getId());
                    newSecKillProduct.setProduct(product);
                    newSecKillProduct.setSeckillProduct(seckillProduct);
                    newSecKillProducts.add(newSecKillProduct);
                }
            }
        }
        model.addAttribute("products", newSecKillProducts);
        return "secKill";
    }

    @RequestMapping("/secKill/detail")
    public String secKillDetail(@RequestParam(value = "productId", required = false) String productId,
                                @RequestParam(value = "message", required = false) String message,
                                Model model, HttpSession session) throws ParseException {
        if (productId == null) {
            return "redirect:/secKill/list";
        } else {
            Product byId = productFeign.getById(Integer.parseInt(productId));
            Shop shop = shopFeign.findById(byId.getShopId());
            model.addAttribute("shop", shop);

            Consumer consumer = consumerFeign.getName((String) session.getAttribute("user"));

            List<Product> products = productFeign.all();
            Random random = new Random();
            List<Integer> rans = new ArrayList<>();
            for (int i = 0; i < products.size(); i++) {
                rans.add(random.nextInt(products.size()));
            }
//            List<Bbs> byProductId = bbsFeign.findByProductId(Integer.parseInt(productId));
            Discount discount = discountFeign.findDiscount(Integer.parseInt(productId));
            model.addAttribute("consumer", consumer);
            model.addAttribute("discount", discount);
//            model.addAttribute("commonNumber", byProductId.size());
            if (products.size() > 8) {
                model.addAttribute("random1", products.get(1));
                model.addAttribute("random2", products.get(2));
                model.addAttribute("random3", products.get(3));
                model.addAttribute("random4", products.get(4));
                model.addAttribute("random5", products.get(5));
                model.addAttribute("random6", products.get(6));
                model.addAttribute("random7", products.get(7));
                model.addAttribute("random8", products.get(8));
            }

            model.addAttribute("products", products);
            String[] color = byId.getColor().split("，");
            for (int i = 0; i < color.length; i++) {
                System.out.println(color[i]);
            }

            model.addAttribute("color", color);
//            model.addAttribute("product", byId);
            session.setAttribute("message", null);
            System.out.println("message" + message);
            model.addAttribute("message", message);
            model.addAttribute("user", session.getAttribute("user"));
            model.addAttribute("warning", session.getAttribute("warning"));
            SeckillProduct start=secKillFeign.StartById(Integer.valueOf(productId));
            model.addAttribute("start",start);
            SeckillProduct skById = secKillFeign.getById(Integer.valueOf(productId));

            SecKillVO secKillVO = new SecKillVO();
            secKillVO.setProduct(byId);
            secKillVO.setSeckillProduct(skById);
            model.addAttribute("product", secKillVO);


            List<Evaluate> evaluates = evaluateFeign.findByProductId(Integer.parseInt(productId));
            //获取评分
            int avg;
            List<Integer> level_avg=new ArrayList<>();
            for (int i=0;i<evaluates.size();i++){
                level_avg.add(evaluates.get(i).getLevel());
            }
            int sum=0;
            for(int i=0;i<level_avg.size();i++){
                sum+= level_avg.get(i);
            }
            if(level_avg.size()==0){
                avg=0;
            }else {
            avg=sum/level_avg.size();}
            //好中差评
            List<Integer> good=new ArrayList<>();
            List<Integer> centre=new ArrayList<>();
            List<Integer> bad=new ArrayList<>();
            for (int i=0;i<evaluates.size();i++){
                if(evaluates.get(i).getLevel()>=4){
                    good.add(evaluates.get(i).getLevel());
                }if(evaluates.get(i).getLevel()>=2&&evaluates.get(i).getLevel()<4){
                    centre.add(evaluates.get(i).getLevel());
                }else {
                    bad.add(evaluates.get(i).getLevel());
                }
            }
            model.addAttribute("good",good);
            model.addAttribute("centre",centre);
            model.addAttribute("bad",bad);
            model.addAttribute("avg",avg);
            model.addAttribute("all",evaluates.size());
            model.addAttribute("goodSize",good.size());
            model.addAttribute("centreSize",centre.size());
            model.addAttribute("badSize",bad.size());
            model.addAttribute("evaluates",evaluates);

            return "secKillDetail";
        }
    }

    @RequestMapping("/secKill/buy")
    public String secKillBuy(Model model, HttpSession session,
                             @RequestParam(required = false, value = "productId") String productId,
                             @RequestParam(required = false, value = "price") String price) {
        Product product = productFeign.getById(Integer.parseInt(productId));
        System.out.println("产品id" + product.getId());
        String user = (String) session.getAttribute("user");
        Consumer consumer = consumerFeign.getName(user);
        Product products = productFeign.getById(Integer.parseInt(productId));
        model.addAttribute("secKill","true");
        model.addAttribute("products", products);
        model.addAttribute("price", Integer.parseInt(price));
        model.addAttribute("consumer", consumer);
        return "buy";
    }

    @RequestMapping("/secKill/pay")
    public ModelAndView secKillPay(Model model, HttpSession session,
                             @RequestParam(required = false,value = "order_bbs")String order_bbs,
                             @RequestParam(required = false,value = "newAddress")ArrayList newAddress,
                             @RequestParam(required = false, value = "productId") String productId,
                             @RequestParam(required = false, value = "price") String price) {
        String user= (String) session.getAttribute("user");
        Consumer consumer = consumerFeign.getName(user);
        Product product = productFeign.getById(Integer.parseInt(productId));
        int i = secKillFeign.secKill(Integer.parseInt(productId), consumerFeign.getName(user).getId());
        if (i == 1) {
            model.addAttribute("message","抢购失败，库存不足");
            model.addAttribute("secKill","true");
            model.addAttribute("products", product);
            model.addAttribute("price", Integer.parseInt(price));
            model.addAttribute("consumer", consumer);
            return new ModelAndView("buy");
        }
        if (i==2){
            model.addAttribute("message","抢购失败， 没人只限购一件！");
            model.addAttribute("secKill","true");
            model.addAttribute("products", product);
            model.addAttribute("price", Integer.parseInt(price));
            model.addAttribute("consumer", consumer);
            return new ModelAndView("buy");
        }else {
            int rand1 = randomNum.RandomNumber1();
            int rand2 = randomNum.RandomNumber2();
            int rand3 = randomNum.RandomNumber2();
            String date = (String.valueOf(new SimpleDateFormat("ss").format(new Date())));
            //三次随机数相加确保订单号不会重复！取日期数字过长不适用int，用long会有精度问题。
            String orderId = rand1 + rand2 + rand3 + date;
            orderFeign.orderAdd(Integer.parseInt(orderId), consumer.getId(), Float.parseFloat(price), Integer.parseInt(productId),
                    1, order_bbs, product.getShopId(), consumer.getAddress(), 0, new Date(), null);
            return new ModelAndView("redirect:http://localhost:1091/order/alipay?out_trade_no="+orderId+
                    "&subject="+product.getName()+"&total_amount="+price+"&body="+order_bbs);
        }
    }
}